package com.ccc.boot.security.config;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 处理授权异常
 *
 * @author superC
 * @version 2.0.0
 * @date 2022/4/20
 */

@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    /**
     * 自定义403处理方案
     *      例如：判断当前请求路径需要赋予指定角色，才能进行访问。若无则会抛出403
     *
     * @param request
     * @param response
     * @param accessDeniedException
     * @date 2022/4/20 21:35
     * @author superC
     */

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write("{\"code\":\"403\",\"message\":\"权限不足，请联系管理员！\"}");
        out.flush();
        out.close();
    }
}
